/**
 * ==================================
 * 风险排行
 * ==================================
 */
import { useRequest } from 'ahooks'
import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState
} from 'react'

import IconFont from '@/components/IconFontAl'

import { Tb } from '../../../BigScreenBase/ModuleTitle'
import WordHScroll from '../../../BigScreenWarn/Components/WordHScroll'
import DisplayCard from '../../Components/DisplayCard'
import ListRanking, { ColumnType } from '../../Components/ListRanking'
import greenRank1 from '../../images/greenRank1.png'
import greenRank2 from '../../images/greenRank2.png'
import greenRank3 from '../../images/greenRank3.png'
import rank1 from '../../images/redRank1.png'
import rank2 from '../../images/redRank2.png'
import rank3 from '../../images/redRank3.png'
import RiskRankingTab, { RiskRankingTabProps } from './RiskRankingTab'
import {
  RiskRankingDataResponse,
  getNameFromDataType,
  getRiskRankingData,
  getTypeNameFromDataType,
  riskRankingTabList,
  riskTypeOptions
} from './data'

const rankImg = [rank1, rank2, rank3]
const greenRankImg = [greenRank1, greenRank2, greenRank3]

export type RiskRankingProps = {
  entId: string
}
export type RiskRankingRef = {
  onRefresh: () => void
}

// 数据类型tab
const DATA_TYPE_REFRESH_PER_MS = 60 * 1000
// 风险类型tab
const RISK_TYPE_REFRESH_PER_MS = 20 * 1000

const RiskRanking = forwardRef<RiskRankingRef, RiskRankingProps>(
  ({ entId }, ref) => {
    const currentDataTypeTabIndexRef = useRef<number>(0)
    const [activeDataTypeTabKey, setActiveDataTypeTabKey] = useState<number>(3)

    const currentRiskTypeTabIndexRef = useRef<number>(0)
    const [activeRiskTypeTabKey, setActiveRiskTypeTabKey] = useState<number>(1)

    const riskRankingTabTimerRef = useRef<any>(null)
    const riskTypeTabTimerRef = useRef<any>(null)

    const [tableData, setTableData] = useState<RiskRankingDataResponse[]>([])

    const [refresh, setRefresh] = useState<number>(0)

    const columns: ColumnType<RiskRankingDataResponse>[] = useMemo(() => {
      return [
        {
          title: '排行',
          key: 'index',
          width: 40,
          align: 'center',
          render(_, record, index) {
            return index < 3 ? (
              <div style={{ height: 16 }}>
                <img
                  src={
                    activeRiskTypeTabKey === 1
                      ? rankImg[index]
                      : greenRankImg[index]
                  }
                  style={{ width: 16, height: 16 }}
                />
              </div>
            ) : (
              index + 1
            )
          }
        },
        {
          title: getNameFromDataType(activeDataTypeTabKey),
          key: 'name',
          width: 180,
          align: 'left',
          render(_, record, index) {
            return (
              <div
                style={{
                  width: 180,
                  paddingRight: 16,
                  // display: "inline-block",
                  boxSizing: 'border-box',
                  overflow: 'hidden',
                  whiteSpace: 'nowrap',
                  color:
                    index < 3
                      ? activeRiskTypeTabKey === 1
                        ? '#FF6666'
                        : '#66CCAA'
                      : undefined
                }}
              >
                {record?.name ? (
                  <WordHScroll key={index}>
                    <span>{record?.name}</span>
                  </WordHScroll>
                ) : null}
              </div>
            )
          }
        },
        {
          title: getTypeNameFromDataType(activeDataTypeTabKey),
          key: 'typeName',
          width: 120,
          render(_, record, index) {
            return (
              <div
                style={{ width: 120, overflow: 'hidden', whiteSpace: 'nowrap' }}
              >
                {record?.typeName ? (
                  <WordHScroll>
                    <span>{record?.typeName}</span>
                  </WordHScroll>
                ) : null}
              </div>
            )
          }
        },
        {
          title: '环比',
          key: 'piont',
          align: 'center',
          render(_, record) {
            return (
              <div>
                {record.piont > 0 ? (
                  <IconFont
                    type="icon-xiangshang"
                    style={{ color: '#FF6666' }}
                  />
                ) : record.piont < 0 ? (
                  <IconFont type="icon-xiangxia" style={{ color: '#66CCAA' }} />
                ) : null}
              </div>
            )
          },
          width: 62
        }
      ]
    }, [activeDataTypeTabKey, activeRiskTypeTabKey])

    useImperativeHandle(ref, () => ({
      onRefresh: () => {
        setRefresh(Math.random())
      }
    }))

    useEffect(() => {
      startInterval()
      startRiskTypeTabInterval()
      return () => {
        stopInterval()
        stopRiskTypeTabInterval()
      }
    }, [])

    useRequest(
      () => {
        return getRiskRankingData({
          entId,
          type: activeDataTypeTabKey,
          sortType: activeRiskTypeTabKey,
          topNum: 10
        })
      },
      {
        onSuccess(data) {
          if (data) {
            setTableData(data)
          }
        },
        refreshDeps: [entId, activeDataTypeTabKey, activeRiskTypeTabKey]
      }
    )

    /**
     * 分险排行标题tab - 切换事件
     *
     * @param option
     */
    const onModuleTitleTabChange = (option: Tb) => {
      const newIndex = riskRankingTabList.findIndex(
        (item) => item.value === option.value
      )

      currentDataTypeTabIndexRef.current = newIndex

      setActiveDataTypeTabKey(option.value as number)

      setRefresh(Math.random())
    }

    /**
     * 分险类型tab - 切换事件
     *
     * @param value
     */
    const onRiskRankingTabChange: RiskRankingTabProps['onChange'] = (
      value: string | number
    ) => {
      const newIndex = riskTypeOptions.findIndex((item) => item.value === value)

      currentRiskTypeTabIndexRef.current = newIndex

      setActiveRiskTypeTabKey(value as number)

      setRefresh(Math.random())
    }

    /**
     * 分险类型tab - 定时器
     */
    function startRiskTypeTabInterval() {
      stopRiskTypeTabInterval()

      riskTypeTabTimerRef.current = setInterval(() => {
        const newIndex =
          (currentRiskTypeTabIndexRef.current + 1) % riskTypeOptions.length
        const newValue = riskTypeOptions[newIndex].value

        currentRiskTypeTabIndexRef.current = newIndex

        setActiveRiskTypeTabKey(newValue as number)
      }, RISK_TYPE_REFRESH_PER_MS)
    }

    function stopRiskTypeTabInterval() {
      riskTypeTabTimerRef.current && clearInterval(riskTypeTabTimerRef.current)
    }

    /**
     * 分险类型tab - 移入事件
     */
    const onRiskRankingTabMouseEnter = () => {
      stopRiskTypeTabInterval()
    }

    /**
     * 分险类型tab - 移出事件
     */
    const onRiskRankingTabMouseLeave = () => {
      startRiskTypeTabInterval()
    }

    /**
     * 分险排行标题tab - 定时器
     */
    function startInterval() {
      stopInterval()
      riskTypeTabTimerRef.current = setInterval(() => {
        const newIndex =
          (currentDataTypeTabIndexRef.current + 1) % riskRankingTabList.length
        const newValue = riskRankingTabList[newIndex].value

        currentDataTypeTabIndexRef.current = newIndex

        setActiveDataTypeTabKey(newValue as number)
      }, DATA_TYPE_REFRESH_PER_MS)
    }

    function stopInterval() {
      riskRankingTabTimerRef.current &&
        clearInterval(riskRankingTabTimerRef.current)
    }

    /**
     * 分险排行标题tab - 移入事件
     */
    function onModuleTitleTabMouseEnter() {
      stopInterval()
    }

    /**
     * 分险排行标题tab - 移出事件
     */
    function onModuleTitleTabMouseLeave() {
      startInterval()
    }

    return (
      <DisplayCard
        title="风险排行"
        height={504}
        moduleTitleTabList={riskRankingTabList}
        onModuleTitleTabChange={onModuleTitleTabChange}
        onModuleTitleTabMouseEnter={onModuleTitleTabMouseEnter}
        onModuleTitleTabMouseLeave={onModuleTitleTabMouseLeave}
        activeTabKey={activeDataTypeTabKey}
        bodyStyle={{ paddingLeft: 0, paddingRight: 0 }}
      >
        <RiskRankingTab
          options={riskTypeOptions}
          onChange={onRiskRankingTabChange}
          activeTabValue={activeRiskTypeTabKey}
          onMouseEnter={onRiskRankingTabMouseEnter}
          onMouseLeave={onRiskRankingTabMouseLeave}
        />
        <div style={{ paddingLeft: 16, paddingRight: 16, height: 364 }}>
          <ListRanking
            // key={refresh}
            dataSource={tableData}
            columns={columns}
            rgbColor={
              activeRiskTypeTabKey === 1 ? '255,102,102' : '102, 204, 170'
            }
            emptyText="暂无风险排行"
          />
        </div>
      </DisplayCard>
    )
  }
)

export default RiskRanking
